var form = layui.form, table = layui.table, $ = layui.jquery, upload = layui.upload, id = getQueryVariable("id"),annexList=[];

var data0 = [{
    id: "1",
    contracttype: "text1",
    productimg: "statics/images/layui-logo.jpg",
    number: "3",
    batchno: "333",
    warehousename:"1",
    productcode:"1"
}, {
    id: "2",
    contracttype: "text1",
    productimg: "statics/images/layui-logo.jpg",
    number: "3",
    batchno: "333",
    warehousename:"1",
    productcode:"2"
}, {id: "3", contracttype: "text1", productimg: "statics/images/layui-logo.jpg", number: "3", batchno: "333",
    warehousename:"1",
    productcode:"3"}];
var data1 = [{
    id: "1",
    filename: "layui-logo.jpg",
    url: "statics/images/layui-logo.jpg",
    uploaddate: "2020-10-01"
}, {id: "2", filename: "layui-logo.jpg", url: "statics/images/layui-logo.jpg", uploaddate: "2020-10-01"}, {
    id: "3",
    filename: "layui-logo.jpg",
    url: "statics/images/layui-logo.jpg",
    uploaddate: "2020-10-01"
}, {id: "4", filename: "layui-logo.jpg", url: "statics/images/layui-logo.jpg", uploaddate: "2020-10-01"}];
var data2 = [{
    id: "1",
    operationtype: "text1",
    theoperator: "text2",
    operationdate: "text3",
    modifythecontent: "text4"
}, {
    id: "2",
    operationtype: "text1",
    theoperator: "text2",
    operationdate: "text3",
    modifythecontent: "text4"
}, {
    id: "3",
    operationtype: "text1",
    theoperator: "text2",
    operationdate: "text3",
    modifythecontent: "text4"
}, {id: "4", operationtype: "text1", theoperator: "text2", operationdate: "text3", modifythecontent: "text4"}];
var data3 =[{id:"1","productcode":"text1",specificationcoding:"text2"},{id:"2","productcode":"text2",specificationcoding:"text2"},{id:"3","productcode":"text3",specificationcoding:"text2"},{id:"4","productcode":"text4",specificationcoding:"text2"},{id:"5","productcode":"text5",specificationcoding:"text2"}];
$('#editor-form').find('input,textarea,select').attr('disabled',true);
if (id != "") {
    form.val("editor-form", {
        "invoicenumber": "进入查看明细",
    })
}
var billInfo=""
var billProducts=[]
$(document).ready(function () {
    $.ajax({
        url: 'billDeclare/selectBillById?billId='+id,
        type: 'GET',
        success: function (date) {
            billInfo=date.data
            showBill(billInfo)
        }
    });
    $.ajax({
        url: 'billDeclare/selectProductAndPartsById?billId='+id,
        type: 'GET',
        success: function (date) {
            billProducts=date.data
            table.reload('storageproductstableid',{
                data:billProducts
            })
        }
    });
    //加载附件
    $.ajax({
        url: 'billDeclare/selectBillFile?type=1&parentId='+id,
        type: 'GET',
        success: function (date) {
            annexList=date.data
            table.reload('attachmenttableid', {data:date.data});
        }
    });

})

function showBill(first){
    $("input[name='invoicenumber']").val(first.invoiceNo);
    $("input[name='contact']").val(first.linker);
    $("input[name='shdate']").val(first.shippingDate);
    $("input[name='exchangerate']").val(first.usdRate);
    $("input[name='rmbexchangerate']").val(first.rmbRate);
    $("input[name='modetransportation']").val(first.transMode);
    $("input[name='invoicetotalamount']").val(first.invoicemoney);
    $("input[name='mdate']").val(first.createTime);
    $("input[name='salescontractno']").val(first.contractNo);
    $("input[name='customercontractno']").val(first.custContractNo);
    $("input[name='actualdischargedateatd']").val(first.atdDate);
    $("input[name='wldate']").val(first.inStockDate);
    $("input[name='salesman']").val(first.salesmanName);
    $("input[name='customername']").val(first.custName);
    $("input[name='currency']").val(first.moneyName);
    $("input[name='businessmodel']").val(first.businessMode);
    $("input[name='theoperator']").val(first.operator);
    $("input[name='place']").val(first.startplace);
    $("input[name='destination']").val(first.endplace);
    $("input[name='settlementway']").val(first.settleMode);
    $("input[name='priceterms']").val(first.priceTerm);
    $("input[name='customsdeclaration']").val(first.billCustmsDeclareNo);
    $("input[name='cdate']").val(first.declarationDate);
    $("input[name='esetddate']").val(first.etdDate);
    $("input[name='endesetddate']").val(first.etaDate);
    $("input[name='signingcompany']").val(first.companyName);
    $("input[name='bank']").val(first.bankName);
    $("input[name='theoperator']").val(first.opName);
    var s="否"
    if(first.whetherCreditGuarantee==1){
        s="是(采购抬头：上海沣奇)"
    }else if (first.whetherCreditGuarantee==2){
        s="是(采购抬头：上海源铢)"
    }
    $("input[name='whetherCreditGuarantee']").val(s);
    $("input[name='creditGuaranteeAmount']").val(first.creditGuaranteeAmount);
    form.render();
}
form.render();

let isContainsRole=false;
getIsContainsRole();

//--产品信息
table.render({
    elem: '#storageproducts',
    id: 'storageproductstableid',
    data: billProducts,
    toolbar: '#storageproductstoolbar',
    cols: [[
        {checkbox: true, fixed: true},
        {field: 'stockNo', width: 120, title: '采购单号', edit: 'text'},
        {field: 'goodsCode', width: 120, title: '产品编码', edit: 'text'},
        {field: 'specCode', width: 120, title: '规格编码', edit: 'text'},
        {field: 'specNo', width: 120, title: '规格说明', edit: 'text'},
        {field: 'producttype', width: 120, title: '产品类型', edit: 'text', templet: function(element){
                var     producttype="";
                if(element.producttype==1){ producttype="成品";}else{producttype="配件";}
                return producttype;
            }},
        //暂无
        // {field: 'customersarticlenumber', width: 120, title: '客户货号', edit: 'text'},
        {field: 'goodsCname', width: 120, title: '中文名称', edit: 'text'},
        {field: 'goodsEname', width: 120, title: '英文名称', edit: 'text'},
        {field: 'goodsCdesc', width: 120, title: '中文描述', edit: 'text'},
        {field: 'goodsEdesc', width: 120, title: '英文描述', edit: 'text'},
        {field: 'goodsNum', width: 120, title: '产品数量', edit: 'text'},
        //数量需要进行调整
        {field: 'mastAmount', width: 120, title: '剩余数量', templet: function(element){
                var  ftotalprice=element.lastAmount;
                if(id!=-1){
                    $.ajax({
                        url: 'billDeclare/selectLastAmontById?proid='+element.declareProductId,
                        type: 'GET',
                        async: false, // 同步
                        success: function (date) {
                            ftotalprice=date.data;
                        }
                    });
                }
                return ftotalprice;
            }},
        {field: 'lastAmount', width: 120, title: '报关数量', edit: 'text'},
        {field: 'goodsUnit', width: 120, title: '单位', edit: 'text'},
        {field: 'funitprice', width: 80, title: '单价', edit: 'text',hide:!isContainsRole},
        //进行计算 金额小计=单价*数量
        {field: 'ftotalprice', width: 120, title: '金额小计', edit: 'text',hide:!isContainsRole},
        {field: 'color', width: 120, title: '颜色', edit: 'text'},
        {field: 'goodsGross', width: 120, title: '毛重', edit: 'text'},
        {field: 'totalGross', width: 120, title: '毛重小计', edit: 'text'},
        {field: 'netweight', width: 120, title: '净重', edit: 'text'},
        {field: 'totalnet', width: 120, title: '净重小计', edit: 'text'},
        {field: 'bulk', width: 120, title: '体积', edit: 'text'},
        //托数=数量/每托量
        {field: 'totalTray', width: 120, title: '托数', edit: 'text'},
        {field: 'trayNumber', width: 120, title: '每托量', edit: 'text'},
        {field: 'piecesNum', width: 120, title: '件数', edit: 'text'},
        {field: 'perpiecesNum', width: 120, title: '每件数量', edit: 'text'},
        //暂无
        // {field: 'paymentpaymentdays', width: 120, title: '付款账期', edit: 'text'},
        {field: 'stockPrice', width: 120, title: '采购单价', edit: 'text'},
        {field: 'stockPrice', width: 120, title: '成本单价', edit: 'text'},
        //成本小计=数量*成本单价
        {field: '', width: 120, title: '成本小计', edit: 'text', templet: function(element){
                var ftotalprice=element.goodsNum*element.stockPrice
                return toDecimal4(ftotalprice);
            }},
        {field: 'outerLenght', title: '外包装长', width: 120, edit: 'text'},
        {field: 'outerWidth', title: '外包装宽', width: 120, edit: 'text'},
        {field: 'outerHeight', title: '外包装高', width: 120, edit: 'text'},
        //进行计算 外包装尺寸=外包装长*外包装宽*外包装高
        {field: '', title: '外包装尺寸', width: 120, edit: 'text', templet: function(element){
                return element.outerLenght+"x"+element.outerWidth+"x"+element.outerHeight;
            }},
        {field: 'supplyerName', width: 120, title: '供应商', edit: 'text'},
        {field: 'clientContractNo', width: 120, title: '客户合同号', edit: 'text'},
        {field: 'saleContractNo', width: 120, title: '外销合同号', edit: 'text'},
        //
        {field: 'hsCode', title: '海关编码', width: 240, templet:'#hsCodeSelect'},
        {field: 'billGoodsCname', title: '报关中文品名', width: 140, edit: 'text'},
        {field: 'billGoodsEname', title: '报关英文品名', width: 140, edit: 'text'},
        {field: 'hsMemo', width: 120, title: '报关要素', edit: 'text'},
        {field: 'addRate', width: 120, title: '增值税率', edit: 'text'},
        {field: 'backRate', width: 120, title: '退税率', edit: 'text'},
        {field: 'declarePrice', title: '报关单价', width: 120, edit: 'text'},
        //报关金额小计=报关单价*数量
        {field: 'totalPrice', title: '报关金小计', width: 120, edit: 'text', templet: function(element){
                var totalPrice=element.declarePrice*element.goodsNum
                return toDecimal4(totalPrice)
            }},
    ]],
    height: 380,
    page: false,
    limit: Number.MAX_VALUE,
});
function toDecimal4(x){
    return  x.toFixed(4)
}
//---附件
table.render({
    elem: '#attachment'
    , data:annexList
    , toolbar: '#attachmenttoolbar'
    , cols: [[
        {field: 'fileName', event:'fileName', title: '文件名', fixed: true}
        , {field: 'uploadTime', title: '上传日期', fixed: true}
        , {fixed: 'right', width: 180, align: 'center', toolbar: '#attachmenteditor', title: '操作'}
    ]]
    , id: 'attachmenttableid'
    , height: 380
});

upload.render({
    elem: '#uploadfile'
    , url: 'billDeclare/uploadFile'
    , field: "uploadify"
    , accept: 'file'
    , multiple: true
    , auto: false
    , bindAction: '#testListAction'
    , choose: function (obj) {
        var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
        //读取本地文件
        obj.preview(function (index, file, result) {
            var tr = $(['<tr id="upload-' + index + '">'
                , '<td>' + file.name + '</td>'
                , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                , '<td>等待上传</td>'
                , '<td>'
                , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                , '</td>'
                , '</tr>'].join(''));

            //单个重传
            tr.find('.demo-reload').on('click', function () {
                obj.upload(index, file);
            });

            //删除
            tr.find('.demo-delete').on('click', function () {
                delete files[index]; //删除对应的文件
                tr.remove();
                uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
            });

            $("#uploadlist").append(tr);
        });
    }
    , parseData: function(res){
        return {
            "code": res.status,
            "count": res.total,
            "data": res.data
        };
    }
    , done: function (res, index, upload) {
        let data = res.data;
        for(var i in data){
            if (data[i].status) { //上传成功
                annexList.push(data[i]);
                var tr = $("#uploadlist").find('tr#upload-' + index)
                    , tds = tr.children();
                tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                tds.eq(3).html(''); //清空操作
                return delete this.files[index]; //删除文件队列已经上传成功的文件
            }
            this.error(index, upload);
        }
    }
    , error: function (index, upload) {
        var tr = $("#uploadlist").find('tr#upload-' + index)
            , tds = tr.children();
        tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
        tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
    }
});

table.on('toolbar(attachmenttable)', function (obj) {
    switch (obj.event) {
        case 'uploadfile':
            $("#uploadlist").html(""); //清空上传列表数据
            layer.open({
                type: 1,
                title: "文件上传",
                area: ['710px', '340px'],
                content: $("#attachmentupload")//引用的弹出层的页面层的方式加载修改界面表单
                , cancel: function (index, layero) {
                    table.reload('attachmenttableid', {data:annexList}); //点击关闭刷新表格
                }
            });
            break;
    }
    ;
});
table.on('tool(attachmenttable)', function (obj) {
    let data = obj.data;
    if (obj.event === 'download') { //下载
        let xmlHttpRequest = new XMLHttpRequest();
        let url = "wjinfo/downloadfile2?filename=" + data.filePath;
        xmlHttpRequest.open('GET', url, true);
        //设置请求头
        xmlHttpRequest.setRequestHeader("Content-type", "application/json")
        xmlHttpRequest.responseType = "blob";
        xmlHttpRequest.send(null);

        xmlHttpRequest.onload = function() {
            let content = xmlHttpRequest.response;
            // 组装a标签
            let elink = document.createElement("a");

            //设置文件下载路径
            elink.download = decodeURIComponent(data.fileName);
            elink.style.display = "none";
            let blob = new Blob([content], { type: 'application/force-download' });

            //解决下载不存在文件的问题，根据blob大小判断
            if(blob.size==0){
                layer.msg('服务器没找到此文件，请联系管理员!');
            }else{
                elink.href = window.URL.createObjectURL(blob);
                document.body.appendChild(elink);
                elink.click();
                document.body.removeChild(elink);
            }

        }
    } else if (obj.event === 'del') {
        layer.confirm('确认删除?', function (index) {
            obj.del();
            let id = data.id;
            for (var i = 0; i < annexList.length; i++) {
                if (annexList[i].id == id) {
                    annexList.splice(i, 1); // 将使后面的元素依次前移，数组长度减1
                    i--; // 如果不减，将漏掉一个元素
                    break;
                }
            }
            layer.msg("删除成功", {icon: 6});
            layer.close(index);
            table.reload('attachmenttableid', {data:annexList}); //ajax删除成功之后刷新表格
        });
    }else   if (obj.event === 'fileName') {
        onLineFile(data.filePath)
    }else if(obj.event === 'submit'){
        //获取头部表单数据
        let req = data.field;
        let billid=id;
        //获取附件数据
        let annexReqs = table.cache["attachmenttableid"];
        let datas = JSON.stringify(annexReqs);
        $.ajax({
            type:"POST",
            dataType:"json",
            contentType: 'application/json',
            data:datas,
            url:"billDeclare/add?id="+billid+"&type=2",
            success:function(res){
                if(res.status == 200){
                    layer.msg("保存成功", {icon: 6});
                }else {
                    layer.msg(res.msg, {icon: 5});
                }
                return false;
            }
        });
    }
});
// table.on('row(attachmenttable)', function(obj){
//     debugger
//     let data = obj.data;
//
// })

//---操作日志
table.render({
    elem: '#otherwarehouselog'
    , data: data2
    , cols: [[
        {field: 'operationtype', title: '操作类型', fixed: true}
        , {field: 'theoperator', title: '操作员'}
        , {field: 'operationdate', title: '操作日期'}
        , {field: 'modifythecontent', title: '修改内容'}
    ]]
    , id: 'logtableid'
    , height: 380
    , limit: 30//显示的数量
    , page: true
});

function getIsContainsRole(){
    $.ajax({
        url: 'billDeclare/isContainsRole',
        async: false, // 同步
        success: function (data) {
            if (data.status==200){
                isContainsRole=data.data;
            }
        }
    });
}